package com.itheima.reggie.controller;

import cn.hutool.core.collection.CollectionUtil;
import com.itheima.reggie.ResultInfo;
import com.itheima.reggie.domain.Dish;
import com.itheima.reggie.service.DishService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

@Slf4j
@RestController
public class DishController {

    @Autowired
    private DishService dishService;
    @Autowired
    private RedisTemplate redisTemplate;

    //查询分类菜品
    @GetMapping("/dish/list")
    public ResultInfo findDishList(Long categoryId, Integer status) {

        //设计键
        String key = "dish_" + categoryId;
        //操作字符串结构的对象
        ValueOperations ops = redisTemplate.opsForValue();
        //先从redis中查询
        List<Dish> dishList = (List<Dish>) ops.get(key);
        if (CollectionUtil.isNotEmpty(dishList)) {
            //返回给前端
            return ResultInfo.success(dishList);
        } else {
            log.info("查询数据库");
          dishList=  dishService.findLsit(categoryId, null);
          //查询数据库后保存到redis
            ops.set(key,dishList);
            //返回
            return ResultInfo.success(dishList);

        }
    }
}
